﻿/*
 *  Param.cs
 *
 *  Copyright (C) 2008 Dreamlusion <dreamlusion@gmail.com>
 *
 *      This program is free software; you can redistribute it and/or
 *      modify it under the terms of the GNU General Public License version
 *      2 as published by the Free Software Foundation.
 *
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;


namespace phpMyAdminToolkit.Common
{
	sealed class Param
	{
		public string Name { get; set; }
		public string Value { get; set; }
	}

	static class ParamExtensions
	{
		public static byte[] ConvertToUrlEncodedParamList(this IEnumerable<Param> list)
		{
			string encodedList = string.Empty;
			foreach (Param p in list)
			{
				encodedList += string.Format("&{0}={1}", HttpUtility.UrlEncode(p.Name), HttpUtility.UrlEncode(p.Value));
			}

			return Encoding.ASCII.GetBytes(encodedList.Trim(new char[] { '&' }));
		}

		/// <summary>
		/// </summary>
		/// <param name="list"></param>
		/// <param name="boundary"></param>
		/// <returns></returns>
		/// <remarks>
		/// http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4
		/// </remarks>
		public static byte[] ConvertToMultipartFormData(this IEnumerable<Param> list, string boundary)
		{
			// Content-Type: multipart/form-data; boundary=<boundary>
			string formData = string.Empty;
			
			foreach (Param p in list)
			{
				formData += string.Format("--{2}\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n", p.Name, p.Value, boundary);
			}

			formData += string.Format("--{0}--", boundary);
			return Encoding.ASCII.GetBytes(formData);
		}

		public static void Add(this List<Param> list, string name, string value)
		{
			list.Add(new Param() { Name = name, Value = value });
		}
	}
}
